<template>
  <PageWrapper title="" contentBackground content="" contentClass="p-4">
    <div class="w-1/3 mx-auto mt-25 border-gray-300">
      <div></div>
      <Card :headStyle="headStyle">
        <template #title>
          <div class="w-full text-center"> 注册 </div>
        </template>
        <BasicForm @register="register">
          <template #validateCode="{ model, field }">
            <FormItemRest>
              <div class="flex items-center gap-2">
                <Input style="flex: 1" v-model:value="model[field]" />
                <Button :disabled="isDisabled" @click="sendCode">{{ btnSendText }}</Button>
              </div>
            </FormItemRest>
          </template>
        </BasicForm>
        <div class="flex justify-center">
          <a-button @click="goHome">返回</a-button>
          <a-button type="primary" class="ml-2" @click="customSubmitFunc">确定</a-button>
        </div>
      </Card>
    </div>
  </PageWrapper>
</template>
<script lang="ts">
  import { BasicForm, useForm } from '/@/components/Form';
  import { defineComponent, computed, onMounted, ref } from 'vue';
  import { FormSchema } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import { useGo } from '/@/hooks/web/usePage';
  import { PageEnum } from '/@/enums/pageEnum';
  import { Card, Input, Form, Row, Col, Button } from 'ant-design-vue';
  import { useRouter } from 'vue-router';

  import {
    getPublicCheckLoginName,
    sendValidateCode,
    registByWx,
    checkMobileRepeat,
  } from '/@/api/system/system';

  import { useUserStore } from '/@/store/modules/user';
  export default defineComponent({
    name: 'FormBasicPage',
    components: {
      BasicForm,
      PageWrapper,
      Card,
      Input,
      Form,
      FormItem: Form.Item,
      Row,
      Col,
      FormItemRest: Form.ItemRest,
      Button,
    },
    setup() {
      const { createMessage } = useMessage();
      const go = useGo();
      const { currentRoute } = useRouter();

      console.log('currentRoute', currentRoute.value);
      const isResetPwd = computed(() => currentRoute.value.params.isResetPwd == 'true');

      const mm = ref('');
      const isDisabled = ref(false);
      const btnSendText = ref('发送');
      const headStyle = ref({
        height: '30px',
        padding: '0 5px',
        backgroundColor: '#0084f4',
        color: 'white',
      });

      onMounted(() => {
        if (currentRoute.value.query.nickName) {
          setFieldsValue({
            loginName: currentRoute.value.query.nickName,
          });
        }
      });

      const schemas: FormSchema[] = [
        {
          field: 'loginName',
          component: 'Input',
          label: '登录账户',
          colProps: { span: 24 },
          required: true,
          componentProps: {
            placeholder: '请输入账户名称',
            autocomplete: 'off',
          },
          rules: [
            {
              required: true,
            },
            {
              validator(_, value) {
                return new Promise((resolve, reject) => {
                  getPublicCheckLoginName({ userName: value })
                    .then((res) => {
                      console.log('res', res);
                      mm.value = res.mm;
                      // 此处因为mm在表单中ifShow为false，所以不能赋值，否则会导致提交时rules抛异常
                      // setFieldsValue({
                      //   mm: mm.value,
                      // });
                      if (res.result == 0) {
                        resolve();
                      } else {
                        if (value) {
                          reject('已存在');
                        } else {
                          reject('请填写登录账户');
                        }
                      }
                    })
                    .catch((err) => {
                      reject(err.msg || '验证失败');
                    });
                });
              },
              trigger: 'blur',
            },
          ],
        },
        {
          field: 'mobile',
          component: 'Input',
          label: '手机号',
          colProps: { span: 24 },
          required: true,
          componentProps: {
            placeholder: '请输入手机号',
          },
          rules: [
            {
              required: true,
            },
            {
              validator(_, value) {
                return new Promise((resolve, reject) => {
                  checkMobileRepeat({ mobile: value })
                    .then((data) => {
                      if (data == 0) {
                        resolve();
                      } else {
                        if (value) {
                          reject('手机号已存在');
                        } else {
                          reject();
                        }
                      }
                    })
                    .catch((err) => {
                      reject(err.msg || '验证失败');
                    });
                });
              },
              trigger: 'blur',
            },
          ],
        },
        {
          field: 'validateCode',
          component: 'Input',
          label: '验证码',
          colProps: { span: 24 },
          required: true,
          componentProps: {
            placeholder: '请输入验证码',
          },
          slot: 'validateCode',
        },
        {
          field: 'mm',
          component: 'Input',
          label: '默认密码',
          colProps: { span: 24 },
          required: true,
          componentProps: {
            placeholder: '请输入密码',
          },
          ifShow: false,
        },
        {
          field: 'pwd',
          component: 'InputPassword',
          label: '密码',
          colProps: { span: 24 },
          required: true,
          componentProps: {
            placeholder: '请输入密码',
            autocomplete: 'new-password',
          },
          ifShow: false,
        },
        {
          field: 'confirmPwd',
          component: 'InputPassword',
          label: '确认密码',
          colProps: { span: 24 },
          required: true,
          componentProps: {
            placeholder: '请输入确认密码',
            autocomplete: 'new-password',
          },
          ifShow: false,
          rules: [
            {
              required: true,
            },
            {
              validator(_, value) {
                return new Promise((resolve, reject) => {
                  console.log('record==>', getFieldsValue());
                  const pwd = getFieldsValue().pwd;
                  if (pwd === value) {
                    resolve();
                  } else {
                    reject('与密码不一致');
                  }
                });
              },
              trigger: 'change',
            },
          ],
        },
      ];

      const [register, { validate, setProps, getFieldsValue, resetFields, setFieldsValue }] =
        useForm({
          labelCol: {
            span: 8,
          },
          wrapperCol: {
            span: 15,
          },
          schemas: schemas,
          actionColOptions: {
            offset: 8,
            span: 15,
          },
          submitButtonOptions: {
            text: '确定',
          },
          showActionButtonGroup: false,
          submitFunc: customSubmitFunc,
        });

      const userStore = useUserStore();
      async function customSubmitFunc() {
        try {
          console.log('customSubmitFunc');
          const formData = await validate();
          console.log('formData', formData);
          setProps({
            submitButtonOptions: {
              loading: true,
            },
          });
          let params = {
            openId: currentRoute.value.query.openId,
            sex: currentRoute.value.query.sex,
            ...formData,
          };
          let data = await registByWx(params);
          userStore.setServerUrl(data.serverInfo.url);
          userStore.setServerInfo(data.serverInfo);
          userStore.setToken(data.Authorization);

          // 不能直接go，因为还需要在afterLoginAction中调用getUISetup，否则界面上会显示为白色
          // go(PageEnum.BASE_HOME);
          await userStore.afterLoginAction(true);

          setProps({
            submitButtonOptions: {
              loading: false,
            },
          });
        } catch (error) {
          console.error(error);
        }
      }

      function goHome() {
        go(userStore.getUserInfo.homePath || PageEnum.BASE_HOME);
      }

      let c = 60;
      async function sendCode() {
        let fields = getFieldsValue();
        console.log('fields', fields);
        if (!fields.mobile) {
          createMessage.warn('请输入手机号');
          return;
        }
        await sendValidateCode({ openId: currentRoute.value.query.openId, mobile: fields.mobile });
        btnSendText.value = '重新发送(' + c + ')';
        isDisabled.value = true;
        c = 60;

        let sint = setInterval(() => {
          c--;
          if (c == 0) {
            btnSendText.value = '发送';
            clearInterval(sint);
            isDisabled.value = false;
          } else {
            btnSendText.value = '重新发送(' + c + ')';
          }
        }, 1000);
      }

      return {
        register,
        resetFields,
        customSubmitFunc,
        goHome,
        isResetPwd,
        isDisabled,
        sendCode,
        btnSendText,
        headStyle,
      };
    },
  });
</script>
<style lang="less" scoped>
  .form-wrap {
    padding: 24px;
    background-color: @component-background;
  }
</style>
